<template>
  <div class="mobile-dashboard">
    <!-- 顶部用户信息 -->
    <div class="user-header">
      <div class="user-info">
        <img :src="$store.getters.avatar" alt="User Avatar" class="avatar" />
        <div class="greeting">
          <h2>{{ $store.getters.name }}，{{ timeOfDay }}好！</h2>
          <p>开始您一天的工作吧！</p>
        </div>
      </div>
    </div>
    <div style="padding: 102px 10px 50px;">
      <!-- 快速统计卡片 -->
      <div class="quick-stats">
        <div class="stat-card" @click="headerToOrderIndex(null)">
          <div class="stat-value">
            {{ projectNumberAndTodoAndRenewed.orderCount || 0 }}
          </div>
          <div class="stat-label">商机数</div>
        </div>
        <div class="stat-card"  @click="toDoPageIndex()">
          <div class="stat-value">{{ total }}</div>
          <div class="stat-label">待办</div>
        </div>
        <div class="stat-card" @click="headerToOrderIndex('0')">
          <div class="stat-value">
            {{ projectNumberAndTodoAndRenewed.isRenewalCount || 0 }}
          </div>
          <div class="stat-label">待续费</div>
        </div>
      </div>

      <!-- 筛选器 -->
      <div class="filter-section">
        <div class="filter-header" @click="toggleFilters">
          <span>筛选条件</span>
          <i :class="['el-icon-arrow-down', { 'is-active': showFilters }]"></i>
        </div>

        <el-collapse-transition>
          <div v-show="showFilters" class="filter-content">
            <el-form :model="queryParams" ref="queryForm" label-width="80px">
              <el-form-item label="年份">
                <el-date-picker
                  v-model="queryParams.year"
                  type="year"
                  placeholder="选择年"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>

              <el-form-item label="季度">
                <quarter-picker
                  v-model="queryParams.quarter"
                  value-format="yyyy-MM-dd"
                  :width="'100%'"
                  clearable
                />
              </el-form-item>

              <el-form-item label="月份">
                <el-date-picker
                  v-model="queryParams.month"
                  type="month"
                  placeholder="选择月"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item label="所属部门" prop="deptId" v-if="$auth.hasRoleOr(['sdl'])">
                <treeselect
                  v-model="queryParams.deptId"
                  :options="deptOptions"
                  :show-count="true"
                  placeholder="请选择归属部门"
                />
              </el-form-item>

              <el-form-item label="所属人">
                <el-select
                  v-model="queryParams.userId"
                  placeholder="请选择所属人"
                  style="width: 100%"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="user in userList"
                    :key="user.userId"
                    :label="user.userName"
                    :value="user.userId"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="所属组" v-if="$auth.hasRoleOr(['sdl', 'gl'])">
                <el-select
                  v-model="queryParams.groupId"
                  placeholder="请选择所属小组"
                  style="width: 100%"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="dict in getGroupList()"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>

              <div class="filter-buttons">
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </div>
            </el-form>
          </div>
        </el-collapse-transition>
      </div>

      <!-- 年度目标 -->
      <div class="financial-card">
        <div class="financial-header">
          <span class="title">年度目标利润</span>
          <div class="amount">{{ target }} 元</div>
        </div>
        <div class="financial-info">
          <div class="info-item">
            <span class="info-label">预计利润</span>
            <span class="info-value">{{ performance.profit || 0 }} 元</span>
          </div>
          <div class="info-item">
            <span class="info-label">完成率</span>
            <span class="info-value"
              >{{
                ((performance.profit / this.target) * 100).toFixed(2) || 0
              }}
              %</span
            >
          </div>
        </div>
        <div class="progress-bar-container">
          <!-- <div class="progress-bar">
            <div class="progress" :style="width: 100%"></div>
          </div> -->
          <el-progress :text-inside="true" :stroke-width="10" :percentage="(Math.round((performance.profit / this.target) * 100) || 0)" :show-text="false"></el-progress>
        </div>
      </div>

      <!-- 业务指标卡片 -->
      <div class="business-metrics">
        <div class="metric-card" @click="toOrderIndex('4')">
          <div class="metric-icon">
            <i class="el-icon-s-order"></i>
          </div>
          <div class="metric-info" >
            <div class="metric-label">待成交</div>
            <div class="metric-value">{{ todo.awaitDeal || 0 }} 个</div>
          </div>
        </div>

        <div class="metric-card" @click="toOrderIndex('5')">
          <div class="metric-icon">
            <i class="el-icon-s-check"></i>
          </div>
          <div class="metric-info">
            <div class="metric-label">待验收</div>
            <div class="metric-value">{{ todo.awaitAcceptance || 0 }} 个</div>
          </div>
        </div>

        <div class="metric-card" @click="toOrderIndex('6')">
          <div class="metric-icon">
            <i class="el-icon-money"></i>
          </div>
          <div class="metric-info">
            <div class="metric-label">待结算</div>
            <div class="metric-value">{{ todo.awaitClear || 0 }} 个</div>
          </div>
        </div>

        <div class="metric-card" @click="toOrderIndex('3')">
          <div class="metric-icon">
            <i class="el-icon-phone"></i>
          </div>
          <div class="metric-info">
            <div class="metric-label">待跟进</div>
            <div class="metric-value">{{ todo.awaitFollowUp || 0 }} 个</div>
          </div>
        </div>

        <div class="metric-card" @click="toCollectPayMoneyIndex('0')">
          <div class="metric-icon">
            <i class="el-icon-bank-card"></i>
          </div>
          <div class="metric-info">
            <div class="metric-label">应付未付</div>
            <div class="metric-value">¥ {{ todo.collectionAmt || 0 }}</div>
          </div>
        </div>
        <div class="metric-card" @click="toCollectPayMoneyIndex('1')">
          <div class="metric-icon">
            <i class="el-icon-wallet"></i>
          </div>
          <div class="metric-info">
            <div class="metric-label">应收未收</div>
            <div class="metric-value">¥ {{ todo.payAmt || 0 }}</div>
          </div>
        </div>
      </div>



      <!-- 图表区域 -->
      <div class="chart-section">
        <div class="chart-container">
          <LineChart class="chart" :dataInfo="performance" @toIndex="chartToOrderIndex"/>
        </div>

        <div class="chart-container">
          <BarChart class="chart" :dataInfo="actualSpending" @toIndex="chartToOrderIndex"/>
        </div>
      </div>

      <div class="chart-section">
        <div class="chart-container">
          <h3>销售额排行</h3>
          <el-table :data="sales" style="width: 100%" height="250">
            <el-table-column type="index" width="50" label="排名">
            </el-table-column>
            <el-table-column
              prop="userName"
              label="姓名"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column prop="dealCount" width="60" label="成交量">
            </el-table-column>
            <el-table-column prop="dealAmountCount" label="成交总金额">
            </el-table-column>
          </el-table>
        </div>

        <div class="chart-container">
          <h3>成交次数客户排行</h3>
          <el-table :data="transactionsCount" style="width: 100%" height="250">
            <el-table-column type="index" width="50" label="排名">
            </el-table-column>
            <el-table-column
              prop="customerName"
              label="客户"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column prop="dealCount" width="60" label="成交量">
            </el-table-column>
            <el-table-column prop="dealAmountCount" label="成交总金额">
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import LineChart from "@/views/dashboard/LineChart.vue";
import BarChart from "@/views/dashboard/BarChart.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { deptTreeSelect, getUserListByStatus } from "@/api/system/user";

import {
  statisticsProjectNumberAndTodoAndRenewed,
  statisticsPerformance,
  statisticsActualSpending,
  statisticsToDo,
  statisticsSales,
  statisticsTransactionsCount,
} from "@/api/crm/statistics";
import { toDoPage } from "@/api/flow/execute";
export default {
  name: "Index",
  components: { LineChart, BarChart, Treeselect },
  // dicts: ["sys_group"],
  computed: {
    timeOfDay() {
      const now = new Date();
      const hour = now.getHours();

      if (hour >= 0 && hour < 6) {
        return "凌晨";
      } else if (hour >= 6 && hour < 12) {
        return "上午";
      } else if (hour >= 12 && hour < 14) {
        return "中午";
      } else if (hour >= 14 && hour < 18) {
        return "下午";
      } else {
        return "晚上";
      }
    },
  },
  watch: {
    "queryParams.deptId": {
      deep: true,
      immediate: true,
      handler(val) {
        this.target = val ? 1500000 : 300000;
      },
    },
  },
  created() {
    this.getDeptTree();
    this.getUserListByStatus();
    this.statisticsProjectNumberAndTodoAndRenewed();
    this.toDoPage();
    this.handleQuery();
  },
  data() {
    return {
      queryParams: {
        userId: this.$store.getters.userId,
        year: new Date().getFullYear() + "-01-01",
        deptId: undefined,
        groupId: undefined,
        quarter: undefined,
        month: undefined,
        week: undefined,
      },
      deptOptions: [],
      userList: [],
      showFilters: false,
      projectNumberAndTodoAndRenewed: {},
      performance: {},
      actualSpending: {},
      todo: {},
      sales: [],
      transactionsCount: [],
      total: 0,
      target: 0,
    };
  },
  methods: {
    headerToOrderIndex(isRenewal){
      this.queryParams.requestType = '0'
      this.queryParams.isRenewal = isRenewal
      this.$router.push({
        path: "/statistics/order",
        query: {
          queryParams: this.queryParams
        }
      });
    },
    toOrderIndex(progess){
      this.queryParams.requestType = '1'
      this.queryParams.progess = progess
      this.$router.push({
        path: "/statistics/order",
        query: {
          queryParams: this.queryParams
        }
      });
    },
    chartToOrderIndex(progess){
      if(progess === '5'){
        this.$router.push({
          path: "/statistics/project",
          query: {
            queryParams: this.queryParams
          }
      });
      } else {
        this.toOrderIndex(progess)
      }
    },
    toCollectPayMoneyIndex(moneyType){
      this.queryParams.moneyType = moneyType
      this.$router.push({
        path: "/statistics/collectPayMoney",
        query: {
          queryParams: this.queryParams
        }
      });
    },
    toDoPageIndex(){
      this.$router.push("/flow/todo");
    },
    toDoPage() {
      toDoPage({ pageNum: 1, pageSize: 10 }).then((response) => {
        this.total = response.total;
      });
    },
    toggleFilters() {
      this.showFilters = !this.showFilters;
    },
    handleQuery() {
      this.statisticsPerformance();
      this.statisticsActualSpending();
      this.statisticsToDo();
      this.statisticsSales();
      this.statisticsTransactionsCount();
    },
    resetQuery() {
      this.queryParams = {
        userId: this.$store.getters.userId,
        year: new Date().getFullYear() + "-01-01",
        deptId: undefined,
        groupId: undefined,
        quarter: undefined,
        month: undefined,
        week: undefined,
      };
      this.handleQuery();
    },
    // 统计商机数量、待续费数据
    statisticsProjectNumberAndTodoAndRenewed() {
      statisticsProjectNumberAndTodoAndRenewed().then((res) => {
        this.projectNumberAndTodoAndRenewed = res.data;
      });
    },
    // 统计业绩数据
    statisticsPerformance() {
      statisticsPerformance(this.queryParams).then((res) => {
        this.performance = res.data;
      });
    },
    // 统计实际支出数据
    statisticsActualSpending() {
      statisticsActualSpending(this.queryParams).then((res) => {
        this.actualSpending = res.data;
      });
    },
    // 统计待办数据数量
    statisticsToDo() {
      statisticsToDo(this.queryParams).then((res) => {
        this.todo = res.data;
      });
    },
    // 获取销售额排行
    statisticsSales() {
      statisticsSales(this.queryParams).then((res) => {
        this.sales = res.data;
      });
    },
    // 成交次数客户排行
    statisticsTransactionsCount() {
      statisticsTransactionsCount(this.queryParams).then((res) => {
        this.transactionsCount = res.data;
      });
    },
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    getUserListByStatus() {
      getUserListByStatus({ status: "0" }).then((res) => {
        this.userList = res.data;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 10px !important;
}

.mobile-dashboard {
  background: #f5f7fa;
  min-height: 100vh;
}

// 用户信息区域
.user-header {
  background: white;
  padding: 16px;
  // margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;

  .user-info {
    display: flex;
    align-items: center;
    gap: 12px;

    .avatar {
      width: 48px;
      height: 48px;
      border-radius: 50%;
    }

    .greeting {
      h2 {
        font-size: 16px;
        margin-bottom: 4px;
        font-weight: 600;
      }

      p {
        font-size: 14px;
        color: #666;
        margin: 0;
      }
    }
  }
}

// 快速统计
.quick-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 16px;

  .stat-card {
    background: white;
    padding: 12px;
    border-radius: 12px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .stat-value {
      font-size: 20px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    .stat-label {
      font-size: 12px;
      color: #666;
    }
  }
}

// 筛选器区域
.filter-section {
  background: white;
  border-radius: 12px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .filter-header {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;

    i {
      transition: transform 0.3s;

      &.is-active {
        transform: rotate(180deg);
      }
    }
  }

  .filter-content {
    padding: 0 16px 16px;

    .el-form-item {
      margin-bottom: 12px;
    }
  }

  .filter-buttons {
    display: flex;
    gap: 12px;
    margin-top: 16px;

    .el-button {
      flex: 1;
    }
  }
}

// 业务指标卡片
.business-metrics {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 16px;

  .metric-card {
    background: white;
    padding: 16px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    gap: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .metric-icon {
      width: 40px;
      height: 40px;
      border-radius: 8px;
      background: #f0f5ff;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #409eff;
      font-size: 20px;
    }

    .metric-info {
      flex: 1;

      .metric-label {
        font-size: 12px;
        color: #666;
        margin-bottom: 4px;
      }

      .metric-value {
        font-size: 18px;
        font-weight: 600;
      }
    }
  }
}

// 财务指标


// 图表区域
.chart-section {
  .chart-container {
    background: white;
    padding: 16px;
    border-radius: 12px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    h3 {
      font-size: 16px;
      margin-bottom: 16px;
    }

    .chart {
      height: 200px;
    }
  }
}

// 响应式调整
@media screen and (min-width: 768px) {
  .business-metrics {
    grid-template-columns: repeat(4, 1fr);
  }

  .chart-section {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }
}

.financial-card {
  padding: 16px;
  margin-bottom: 20px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  font-family: Arial, sans-serif;
}

.financial-header {
  text-align: center;
  margin-bottom: 16px;
}

.financial-header .title {
  font-size: 16px;
  color: #666;
}

.financial-header .amount {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-top: 8px;
}

.financial-info {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  font-size: 14px;
  color: #999;
}

.info-value {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.progress-bar-container {
  margin-top: 16px;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.progress {
  height: 100%;
  background: #409eff;
  /* 蓝色代表进度 */
  border-radius: 4px;
  transition: width 0.3s ease;
}
</style>
